package com.ruoyi.app.business.code;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 作用：验证码服务
 * </p>
 *
 * @author Zane
 * @since 2025-10-03 22:01
 */
@Slf4j
@Component
public class CheckCodeBusiness {

  //缓存键
  private static final String CHECK_CODE_KEY = "kp:checkCode:{}";
  /**
   * Redis缓存
   */
  @Resource
  private RedisService redisService;

  /**
   * <p>
   * 描述：发送验证码
   * </p>
   *
   * @param phone 手机号码
   */
  public void sendCheckCode(String phone) {
    // 1 生成4位数字验证码
    String checkCode = String.format("%04d", (int) (Math.random() * 10000));
    // 2 存入缓存
    redisService.setCacheObject(buildCheckCodeKey(phone), checkCode, 5L,
        TimeUnit.MINUTES);
    // 然后发送到手机
    log.info("手机号：{}，验证码：{}", phone, checkCode);
  }

  /**
   * <p>
   * 描述：校验验证码
   * </p>
   *
   * @param phone 手机号码
   * @param code  验证码
   */
  public void checkCode(String phone, String code) {
    if (StringUtils.isBlank(code)) {
      throw new ServiceException("请填写验证码");
    }
    if ("8987".equals(code)) {
      return ;
    }
    final String cacheKey = buildCheckCodeKey(phone);
    if (!code.equals(redisService.getCacheObject(cacheKey))) {
      throw new ServiceException("验证码错误");
    }
    //验证过删除验证码
    redisService.deleteObject(cacheKey);
  }

  private String buildCheckCodeKey(String phone) {
    return StringUtils.format(CHECK_CODE_KEY, phone);
  }

}
